package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.OrderService;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ReportServiceImpl implements ReportService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        //    private String dateList;
        //
        //    //营业额，以逗号分隔，例如：406.0,1520.0,75.0
        //    private String turnoverList;

        //先把日期用dateList存起来
        List<LocalDate> dateList = new ArrayList<>();

        while (!begin.equals(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(begin);

        //把对应日期的营业额用turnoverList存起来;
        List<BigDecimal> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime earliest = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime latest = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("earliest", earliest);
            map.put("latest", latest);
            map.put("status", Orders.COMPLETED);
            //select count(amount) from orders  where status = ? and order_time > earliest and order_time < latest
            BigDecimal amount = orderMapper.queryForAmount(map);
            //如果一个订单都没有，金额为0
            if (amount == null) {
                amount = BigDecimal.valueOf(0.0);
            }
            turnoverList.add(amount);
        }

        //封装对象
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtils.join(dateList, ","));
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList, ","));
        return turnoverReportVO;
    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //日期
        List<LocalDate> dateList = new ArrayList<>();

        while (!begin.equals(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(begin);

        //统计用户总量
        Map map = new HashMap<>();
        List<Long> allUsers = new ArrayList<>();
        for (LocalDate date : dateList) {
            //媒体条件
            LocalDateTime latest = LocalDateTime.of(date, LocalTime.MAX);
            map.put("latest", latest);

            Long allUser = userMapper.userStatistics(map);
            if (allUser == null) {
                allUser = 0L;
            }

            allUsers.add(allUser);
        }

        //统计新增用户数量
        List<Long> newUsers = new ArrayList<>();
        for (LocalDate date : dateList) {
            //媒体条件
            LocalDateTime earliest = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime latest = LocalDateTime.of(date, LocalTime.MAX);
            map.put("earliest", earliest);
            map.put("latest", latest);

            Long newUser = userMapper.userStatistics(map);
            if (newUser == null) {
                newUser = 0L;
            }

            newUsers.add(newUser);
        }
        //封装数据
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(dateList, ","));
        userReportVO.setNewUserList(StringUtils.join(newUsers, ","));
        userReportVO.setTotalUserList(StringUtils.join(allUsers, ","));
        return userReportVO;
    }

    /**
     * 订单统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //日期列表
        List<LocalDate> dateList = new ArrayList<>();

        while (!begin.equals(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(begin);

        Map map = new HashMap();
        //订单总数
        Integer totalOrderCount = orderMapper.orderStatistics(map);
        //有效订单数
        map.put("status", Orders.COMPLETED);
        Integer validOrderCount = orderMapper.orderStatistics(map);
        map.remove("status");
        //订单完成率
        Double orderCompletionRate = (double) validOrderCount / (double) totalOrderCount;
        //每日订单数 select count(*) from orders where order_time >  earliest and order_time < latest

        List<Integer> ordersDayNum = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime earliest = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime latest = LocalDateTime.of(date, LocalTime.MAX);

            map.put("earliest", earliest);
            map.put("latest", latest);

            Integer orderNum = orderMapper.orderStatistics(map);
            ordersDayNum.add(orderNum);

        }

        //每日有效订单数 select count(*) from orders where order_time >  earliest and order_time < latest and status = complete
        List<Integer> ordersDayNumValid = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime earliest = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime latest = LocalDateTime.of(date, LocalTime.MAX);

            map.put("earliest", earliest);
            map.put("latest", latest);
            map.put("status", Orders.COMPLETED);

            Integer orderNum = orderMapper.orderStatistics(map);
            ordersDayNumValid.add(orderNum);
        }

        //封装对象
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(ordersDayNum, ","))
                .validOrderCountList(StringUtils.join(ordersDayNumValid, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return orderReportVO;
    }

    /**
     * 查询销量top10
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        Map map = new HashMap<>();

        //日期
        LocalDateTime earliest = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime latest = LocalDateTime.of(end, LocalTime.MAX);

        map.put("earliest", earliest);
        map.put("latest", latest);
        map.put("status", Orders.COMPLETED);
        // 查询
        List<GoodsSalesDTO> top10 = orderMapper.top10(map);
        // 流式编程，将名称和销量单独拿出来成为两个集合

        List<String> names = top10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = top10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        //封装对象
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
        return salesTop10ReportVO;
    }
}
